<?php

class ConfigController extends Controller
{
    public $layout = '//layouts/main';
    public $defaultAction = 'manage';

    public function actionManage()
    {
        $model = new MsggConfig('search');
        if (isset($_GET['MsggConfig'])) {
            $model->attributes = $_GET['MsggConfig'];
        }
        if (isset($_GET['searchKey'])) {
            $model->searchKey = $_GET['searchKey'];
        }
        $this->render('manage', array(
            'model' => $model,
        ));
    }

    public function actionCopy()
    {
        $id = $this->getQuery('get', 'id', null);
        if (!empty($id)) {
            $model = MsggConfig::model()->findByPk($id)->copy();
            if ($model) {
                $this->render('create', array(
                    'model' => $model,
                ));
                return;
            } else {
                Yii::app()->user->setFlash('alert-failure', 'Copy failed');
            }
        } else {
            Yii::app()->user->setFlash('alert-failure', 'Copy failed');
        }
        $this->redirect($this->defaultAction);

    }

    public function actionCreate()
    {
        $model = new MsggConfig();
        if (isset($_POST['MsggConfig'])) {
            $model->attributes = $_POST['MsggConfig'];
            if ($model->save()) {
                Yii::app()->user->setFlash('alert-success', 'Create Success');
                $this->redirect($this->defaultAction);
            } else {
                Yii::app()->user->setFlash('alert-failure', 'Create failed');
            }
        } else {
            $model->level = MsggConfig::DEFAULT_LEVEL;
            $model->try = MsggConfig::DEFAULT_TRY;
        }
        $this->render('model', array(
            'model' => $model,
        ));
    }

    public function actionUpdate()
    {
        if (isset($_GET['id'])) {
            $model = MsggConfig::model()->findByPk($_GET['id']);
            if ($model) {
                if (isset($_POST['MsggConfig']) && ($model->attributes = $_POST['MsggConfig'])) {
                    if ($model->save()) {
                        Yii::app()->user->setFlash('alert-success', 'Update Success');
                        $this->redirect(array($this->defaultAction));
                    } else {
                        if ($model->hasErrors('status')) {
                            Yii::app()->user->setFlash('alert-failure', 'Update failure , the config can\'t work  and  error is ' . $model->getError('status'));
                        }
                    }
                }
                $this->render('model', array(
                    'model' => $model,
                ));
                return;
            }
        }
        Yii::app()->user->setFlash('alert-failure', "Update failure");
        $this->redirect(array($this->defaultAction));
    }


    public function actionSwitch()
    {
        $id = $this->getQuery('get', 'id', null);
        $model = MsggConfig::model()->findByPk($id);
        if ($model) {
            $model->status = $model->isOpen() ? MsggConfig::STATUS_CLOSE : MsggConfig::STATUS_OPEN;
            if ($model->save()) {
                if ($model->isClose() && !MsggConfig::model()->count('type=:type and status=:status', [':type' => $model->type, ':status' => MsggConfig::STATUS_OPEN])) {
                    Yii::app()->user->setFlash('alert-success', "Switch Success Notice you have closed the last open channel in  {$model->type}");
                } else {
                    Yii::app()->user->setFlash('alert-success', "Switch Success");
                }
            } else {
                Yii::app()->user->setFlash('alert-failure', 'Switch failure');
            }
        } else {
            Yii::app()->user->setFlash('alert-failure', 'Switch failure');
        }
        $this->redirect($this->defaultAction);
    }

    public function actionVerified()
    {
        if (!empty($_GET['id'])) {
            $id = $this->getQuery('get', 'id', null);
            $model = MsggConfig::model()->findByPk($id);
            if (empty($model)) {
                Yii::app()->user->setFlash('alert-failure', 'verified failure');
            } else {
                $result = $model->verify();
                if (!$result || $result['code'] != 0) {
                    Yii::app()->user->setFlash('alert-failure', 'verified failure:' . json_encode($result));
                } else {
                    Yii::app()->user->setFlash('alert-success', 'verified success:' . json_encode($result));
                }
            }
        }
        $this->redirect($this->defaultAction);
    }

    public function actionAbandon()
    {
        if (Yii::app()->request->isAjaxRequest) {
            $result = 'Success';
            $id = $this->getQuery('get', 'id', null);
            $model = MsggConfig::model()->findByPk($id);
            if ($model) {
                if (!$model->isOpen()) {
                    if ($model->delete()) {
                        $result = 'Success';
                    } else {
                        $result = 'delete failure';
                    }
                } else {
                    $result = 'you should close it before you want to delete it';
                }
            }
            echo $result;
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    public function actionTest()
    {
        if (Yii::app()->request->isAjaxRequest) {
            $result = 'Success';
            $verifiedResult =MsggConfig::verifiedAll();
            if($verifiedResult['code']==0)
            {
                echo $result;
            }
            else{
                echo json_encode($verifiedResult);
            }

        } else {
            $this->render('test', array());
        }
    }


    public function colRevise($data, $row, $c)
    {
        $name = $c->name;
        switch ($name) {
            case 'name':
                return $data->name;
                break;
            case 'type':
                return $data->type;
                break;
            case 'config':
                $res = '';
                foreach (json_decode($data->config, true) as $key => $value) {
                    if (is_array($value)) {
                        $value = implode(',', $value);
                    }
                    $res .= '<div class="row">';
                    $res .= '<div style=" white-space:nowrap; overflow:hidden; text-overflow:ellipsis;" class="col-xs-12" title="' . $value . '" >' . $key . ' = ' . $value;
                    $res .= '</div>';
                    $res .= '</div>';
                }
                return $res;
                break;
            case 'try':
                return $data->try;
                break;
            case 'status':
                $status = $data->status;
                $color = $data->isOpen() ? 'green' : 'red';
                $title = MsggConfig::getOptions('status')[$status];
                $res = '';
                $res .= '<div class="row">';
                $res .= vsprintf('<div class="col-xs-12"  style = "color:%s" >%s</div>', [$color, $title]);
                $res .= '</div>';
                return $res;
                break;
            case 'level':
                return $data->level;
                break;
            case 'button':
                $params = [];
                $res = '';
                //edit
                $params[] = Yii::app()->getController()->createUrl("update", array("id" => $data->id,));
                $res .= '<a class ="fa fa-pencil" title="编辑" href="%s"></a>';
                //switch
                $params[] = $data->isOpen() ? 'on' : 'off';
                $params[] = $data->isOpen() ? "关闭" : "开启";
                $params[] = Yii::app()->getController()->createUrl("switch", array("id" => $data->id,));
                $res .= '<a class ="fa fa-toggle-%s"  title="%s" href="%s"></a>';
                //verified
                $params[] = '验证';
                $params[] = Yii::app()->getController()->createUrl("verified", array("id" => $data->id,));
                $res .= '<a class ="fa fa-cogs" title="%s" href="%s"></a>';
                //copy
                $params[] = Yii::app()->getController()->createUrl("copy", array("id" => $data->id,));
                $res .= '<a class ="fa fa-files-o" title="复制" href="%s"></a>';
                //delete
                if (!$data->isOpen()) {
                    $params[] = '删除';
                    $params[] = Yii::app()->getController()->createUrl("abandon", array("id" => $data->id,));
                    $params[] = $data->type;
                    $res .= '<a class ="delete fa fa-trash  tooltip="delete" title="%s"  href="%s" type="%s"></a>';
                }
                return vsprintf($res, $params);
                break;
            default:
                return $data->name;
        }
    }
}